public class Practice2 {
    //https://leetcode.cn/problems/perfect-squares/description/
    //完全背包, 这一题想法挺有趣的, 我开始都没想到可以背包
    //非优化版本
    public int numSquares(int n) {
        int t = (int)Math.sqrt(n);
        int[][] dp = new int[t + 1][n + 1];
        int INF = 0x3f3f3f3f;
        for(int i = 1;i <= n;i++){
            dp[0][i] = INF;
        }
        for(int i = 1;i <= t;i++){
            int cur = i * i;
            for(int j = 0;j <= n;j++){
                dp[i][j] = dp[i - 1][j];
                if(j - cur >= 0){
                    dp[i][j] = Math.min(dp[i][j],dp[i][j - cur] + 1);
                }
            }
        }
        return dp[t][n];
    }
    //空间优化
    public int numSquares(int n) {
        int t = (int)Math.sqrt(n);
        int[] dp = new int[n + 1];
        int INF = 0x3f3f3f3f;
        for(int i = 1;i <= n;i++){
            dp[i] = INF;
        }
        for(int i = 1;i <= t;i++){
            int cur = i * i;
            for(int j = 0;j <= n;j++){
                if(j - cur >= 0){
                    dp[j] = Math.min(dp[j],dp[j - cur] + 1);
                }
            }
        }
        return dp[n];
    }
}
